package com.fnzx.controller;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.OSSObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fnzx.dao.CommentDao;
import com.fnzx.entity.CommentEntity;
import com.fnzx.entity.DemandEntity;
import com.fnzx.entity.UserEntity;
import com.fnzx.entity.vo.CommentVo;
import com.fnzx.service.CommentService;
import com.fnzx.service.DemandService;
import com.fnzx.service.UserService;
import com.fnzx.util.PageUtils;
import com.fnzx.util.R;
import com.fnzx.util.oss.OssUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2021-10-23 22:20:01
 */
@RestController
@RequestMapping("iot/comment")
@Api(tags = "评论板块")
public class CommentController {
    @Autowired
    private CommentService commentService;

    @Autowired
    private DemandService demandService;
    @Autowired
    private UserService userService;

    @ApiOperation(value = "同时获取一级二级评论",notes = "获取评论")
    @GetMapping("/list")
    public R remark(@RequestParam(value = "demandId") Long demandId){
        List<CommentVo> all = commentService.getAll(demandId);
        List<Object> map=new ArrayList<>();
        int i=0;
        for(CommentVo vo:all){
            List<CommentVo> child = commentService.findChild(vo.getCommentEntity().getId());
            List<Object> list = new ArrayList<>();
            list.add(all);
            list.add(child);
            map.add(i,list);
            i++;
        }
        return R.ok().put("remarks", map);
    }

    @ApiOperation(value = "获取下一级评论",notes = "通过评论id查询该下一级评论")
    @GetMapping("/getSon")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "当前页",paramType = "query",required = true,dataType = "String"),
            @ApiImplicitParam(name = "limit",value = "每页记录数",paramType = "query",required = true,dataType = "String"),

            @ApiImplicitParam(name = "commentId",value = "commentId",paramType = "path",required = true,dataType = "String")
    })
    public R getSon(@ApiIgnore@RequestParam Map<String,Object> params){
        PageUtils page = commentService.queryPageByPa(params);
        return R.ok().put("remarks", page);
    }

    @ApiOperation(value = "获取一级评论",notes = "通过需求id查询该一级评论")
    @GetMapping("/getParent")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "当前页",paramType = "query",required = true,dataType = "String"),
            @ApiImplicitParam(name = "limit",value = "每页记录数",paramType = "query",required = true,dataType = "String"),
            @ApiImplicitParam(name = "demandId",value = "需求id",paramType = "path",required = true,dataType = "String")
    })
    public R getParent(@ApiIgnore @RequestParam Map<String,Object> params){
        PageUtils page = commentService.queryPageByDe(params);
        return R.ok().put("remarks", page);
    }

    @ApiOperation(value = "获取下一级评论 无分页",notes = "通过评论id查询该下一级评论")
    @GetMapping("/getNext")
    public R getNext(@RequestParam(value = "commentId") Long commentId){
        List<CommentVo> vo = commentService.findChild(commentId);
        return R.ok().put("remarks", vo);
    }

    @ApiOperation(value = "添加评论(整体)", notes = "添加评论,一级评论parentId为0，{\n" +
            "\t\"commentContent\": \"fsf\",\n" +
            "\t\"demandId\": ,\n" +
            "\t\"parentId\": ,\n" +
            "\t\"pushlisherId\": \n" +
            "\t\"docfilesurl\": \n"+
            "}")
    @PostMapping("/add")
    public R add(@RequestBody CommentEntity commentEntity){
        commentService.save(commentEntity);
        return R.ok();
    }
    @ApiOperation(value = "后台页面-删除", notes = "删除需求,可多个")
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids,@RequestHeader String token){
        if(ids.length !=0 && ids !=null){
           commentService.removeByIds(Arrays.asList(ids));
            return R.ok();
        }
        return R.ok("id不能为空");
    }

    @ApiOperation(value = "评论id查询",notes = "通过评论id查询")
    @GetMapping("/info/{id}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "评论id",paramType = "path",required = true,dataType = "String"),
    })
    public R getComment(@PathVariable("id") Long id){
        CommentEntity comment = commentService.getById(id);
        UserEntity user = userService.getOne(new QueryWrapper<UserEntity>().eq("id", comment.getPushlisherId()));
        CommentVo commentVo = new CommentVo(comment, user);
        return R.ok().put("commentVo",commentVo);
    }

    /**
     * 上传附件
     */
    @ApiOperation(value = "上传附件", notes = "上传文件到阿里云oss")
    @PostMapping("/fileUpload")
    public R fileUpload(MultipartFile file) throws IOException {
        //获取上传文件
        String url = OssUtils.upload(file);
        return R.ok(url);
    }

    /**
     * 下载附件
     */
//    @ApiOperation(value = "下载文档",notes = "通过评论id查下载文档")
//    @PostMapping("/download")
//    public R fileDownload(@RequestParam("id") Long commentId,
//                          @RequestParam("localPath") String localPath,
//                          @RequestParam("saveName") String saveName){
//        CommentEntity comment= commentService.getById(commentId);
//        String url1 = comment.getDocFilesUrl();
//
//        //  String localPath="D:\\Downloads\\";
//        // String saveName="1.doc";
//        OssUtils.down(url1,localPath,saveName);
//
//        return R.ok();
//    }

    @ApiOperation(value = "下载附件", notes = "下载附件")
    @PostMapping("/downloadAttachment")
    public String downloadAttachment(@RequestParam("id") Long commentId,@RequestParam("fileName") String fileName,
                                HttpServletRequest request, HttpServletResponse response) {

        CommentEntity comment= commentService.getById(commentId);
        String downLoadPath = comment.getDocFilesUrl();
        //这里获取的下载链接 http://sk.sit.fosuntech.cn/group1/M00/00/72/CqYKHVn69wyAMl6YAAVf953sp4Y075.pdf
        //String downLoadPath = templateService.getDownloanUrl(imageId);
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {

            //如果不存在乱码的情况可以忽略，由于请求参数文件名为中文，到后台会乱码，考虑操作系统和客户端浏览器默认编码
            //判断服务器操作系统，本地开发使用windows
            String os = System.getProperty("os.name");
            if(os.toLowerCase().indexOf("windows") != -1){
                fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
            }else{
                //判断浏览器
                String userAgent = request.getHeader("User-Agent").toLowerCase();
                if(userAgent.indexOf("msie") > 0){
                    fileName = URLEncoder.encode(fileName, "ISO-8859-1");
                }
            }
            //响应二进制流
            response.setContentType("application/octet-stream");
            response.reset();//清除response中的缓存

            //跨域
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type");

            //根据网络文件地址创建URL
            URL url = new URL(downLoadPath);
            //获取此路径的连接
            URLConnection conn = url.openConnection();
            Long fileLength = conn.getContentLengthLong();//获取文件大小
            //设置reponse响应头，真实文件名重命名，就是在这里设置，设置编码
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + fileName);
            response.setHeader("Content-Length", String.valueOf(fileLength));

            bis = new BufferedInputStream(conn.getInputStream());//构造读取流
            bos = new BufferedOutputStream(response.getOutputStream());//构造输出流
            byte[] buff = new byte[1024];
            int bytesRead;
            //每次读取缓存大小的流，写到输出流
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            response.flushBuffer();//将所有的读取的流返回给客户端
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try{
                if(null != bis){
                    bis.close();
                }
                if(null != bos){
                    bos.close();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        return null;
    }

}
